/*
 * @FileName: app_fault.c
 * @Author: GreyQiu qiushaogui@aikosolar.com
 * @Date: 2023-07-18 10:14:16
 * @LastEditors: GreyQiu qiushaogui@aikosolar.com
 * @LastEditTime: 2023-09-18 08:57:35
 * @Description: 
 * 
 * Copyright (c) 2023, All Rights Reserved. 
 */

#include "bsp.h"
#include "fault.h"
#include "app_fault.h"
#include "app_analog.h"

uint16_t g_fault_bits = 0x0000; // 16位数，每一位代表对应fault的状态

/**
 * @description: 故障表
 */
fault_t ft_tbl[FAULT_NUM] =
{
    {.id = FAULT_VAC_UVP,  .flag = false, .singal_addr = &(Vrms.vRms),  .polarity = LOW,  .auto_clear = ENABLE, .threshold = 45.0f, .trig_time = 1000, .recovery_time = 1000},
    {.id = FAULT_VAC_OVP, .flag = false, .singal_addr = &(Vrms.vRms), .polarity = HIGH, .auto_clear = ENABLE, .threshold = 290.0f, .trig_time = 1000,  .recovery_time = 1000},

    {.id = FAULT_VAC_UFP,  .flag = false, .singal_addr = &(Vrms.acFreqAvg),  .polarity = LOW,  .auto_clear = ENABLE, .threshold = 45.0f, .trig_time = 1000, .recovery_time = 1000},
    {.id = FAULT_VAC_OFP, .flag = false, .singal_addr = &(Vrms.acFreqAvg), .polarity = HIGH, .auto_clear = ENABLE, .threshold = 55.0f, .trig_time = 1000,  .recovery_time = 1000},
};

/**
 * @description: 故障模块主任务
 * @return 无
 */
void app_fault_run(void)
{
    for (uint16_t id = 0; id < FAULT_NUM; id++) {
        fault_check(&ft_tbl[id]);

        if (ft_tbl[id].flag == true) {
            g_fault_bits |= (1 << id); // 对应bit位置1
        } else {
            g_fault_bits &= (~(1 << id)); // 对应bit位清0
        }
    }
}

/**
 * @description: 检查故障被触发
 * @param id 故障id
 * @return 无
 */
bool app_fault_is_trig(fault_id_t id)
{
    return ft_tbl[id].flag;
}

/**
 * @description: 检查故障被触发
 * @param id 故障id
 * @return 无
 */
uint16_t app_fault_get_bits(void)
{
    return g_fault_bits;
}

/**
 * @description: 设置故障标志位
 * @param id 故障id
 * @return 无
 */
void app_fault_set_bit(uint16_t bit_mask)
{
    g_fault_bits |= bit_mask;
}

/**
 * @description: 清楚故障标志位
 * @param id 故障id
 * @return 无
 */
void app_fault_clear_bit(uint16_t bit_mask)
{
    g_fault_bits &= (~bit_mask);
}

/**
 * @description: 读取故障标志位
 * @param id 故障id
 * @return 无
 */
bool app_fault_get_bit(uint16_t bit_mask)
{
    return (g_fault_bits & bit_mask) == bit_mask;
}
